Online-Academy
Look, Read, Understand, Apply

Wrapper AutoBoxing Unboxing

Wrapper Class in Java

A Wrapper class is a class that converts a primitive data type into an object. Each primitive type has a corresponding wrapper class.

Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
int num = 1098;
Integer obj = Integer.valueOf(num);   // Manual wrapping
System.out.println(obj);

Uses of Wrapper Classes:

  • Required in Collections (ArrayList, HashMap, etc.) because they store objects, not primitives.
  • Provide utility methods like parseInt(), compareTo(), etc.
  • Support object-oriented programming concepts.

Autoboxing

Autoboxing is the automatic conversion of a primitive data type into its corresponding wrapper object by the Java compiler.

int a = 20;
Integer obj = a;   // Autoboxing

System.out.println(obj);

Unboxing

Unboxing is the automatic conversion of a wrapper object into its corresponding primitive data type.

Integer obj = 30;
int a = obj;   // Unboxing

System.out.println(a);

Complete Example

public class WrapperExample {
    public static void main(String[] args) {

        // Autoboxing
        int x = 100;
        Integer obj = x;

        // Unboxing
        Integer y = 200;
        int num = y;

        System.out.println("Autoboxing: " + obj);
        System.out.println("Unboxing: " + num);
    }
}
  • Wrapper Class: Converts primitive data types into objects.
  • Autoboxing: Automatic conversion from primitive -> wrapper object.
  • Unboxing: Automatic conversion from wrapper object -> primitive.